package cn.wolfcode.p2p.base.controller;

import cn.wolfcode.p2p.Exception.CustomException;
import cn.wolfcode.p2p.Exception.ErrorCode;
import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.service.IIpLogService;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.util.JSONResultUtil;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 前台用户登录
 */
@Controller
public class LoginController {
    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private IIpLogService ipLogService;

    /**
     * 保存登录信息以及登陆记录
     * @param loginInfo
     * @return
     */

    @RequestMapping("/login")
    @ResponseBody
    public Object login(LoginInfo loginInfo){
        try {
            loginInfoService.login(loginInfo, LoginInfo.TYPE_WEBSITE);
            ipLogService.save(loginInfo, IpLog.LOGIN_STATE_SUCCESS,LoginInfo.TYPE_WEBSITE);
        } catch (CustomException e) {
            e.printStackTrace();
            ipLogService.save(loginInfo,IpLog.LOGIN_STATE_FAIL,LoginInfo.TYPE_WEBSITE);
            throw new CustomException(ErrorCode.LOGIN_FAIL);
        }catch (Exception e) {
            e.printStackTrace();
            ipLogService.save(loginInfo,IpLog.LOGIN_STATE_FAIL,LoginInfo.TYPE_WEBSITE);
            throw new RuntimeException();
        }
        return JSONResultUtil.jsonResult();
    }

    @RequestMapping("/logout")
    public String logout(){
        UserContext.getSession().invalidate();
        return "redirect:/login.html";
    }
}
